using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Unity.Plastic.Newtonsoft.Json;
using Vector2 = UnityEngine.Vector2;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
using Unity.VisualScripting;

namespace MeEditor
{
    public class Item
    {
        public Object prefab;
        public PrefabItem prefabItem;
        public string guid;
        public Texture tex;
        public bool dynamicTex = false;
    }
 
    [System.Serializable]
    public class Category
    {
        public int Id { get; set; }
        public PrefabType Type { get; set; }
        public string Name { get; set; }
        //设置为prefabItem 当前值默认获取path
        // public List<string> Prefabs { get; set; }
        public List<PrefabItem> Prefabs { 
            get; 
            set;
        }
    }
    public enum PrefabType
    {
        prefab,
        image
    }
    [System.Serializable]
    public class PrefabItem
    {
        //构建函数
  
        public PrefabType type = PrefabType.prefab;
        public string name;
        public string guid;
        public string path;
        public string desc;
        public string image;
    }
    //父类菜单项
    [System.Serializable]
    public class SystemFather
    {
        public int Id { get; set; }
        public string MenuPath;
        public PrefabType Type { get; set; }
        public string Name { get; set; }
        public List<Category> Children { get; set; }
        public List<PrefabItem> Prefabs { get; set; }
        // public List<string> Prefabs { get; set; }
    }
 
    public class UXPreabWin : EditorWindow
    {
        private static int _labelDefaultFontSize;
        //设置选中按钮的样式
        private GUIStyle defaultButtonStyle;
        private GUIStyle selectedButtonStyle;
        //创建多维数组
        [MenuItem("MeEditor/UXWindow", false, 9)]
        static void OpenPrefabTool()
        {
            _labelDefaultFontSize = EditorStyles.label.fontSize;
            UXPreabWin prefabWin = (UXPreabWin)EditorWindow.GetWindow<UXPreabWin>(false, "UX预设管理", true);
            prefabWin.autoRepaintOnSceneChange = true;
            prefabWin.Show();
        }
        //prefabWin 右侧添加菜单
        private GUIStyle  _toolbarButtonStyle;
        private void ShowButton(Rect position)
        {
            if (_toolbarButtonStyle == null)
            {
                _toolbarButtonStyle = new GUIStyle(GUI.skin.button)
                {
                    padding = new RectOffset()
                };
            }
            float buttonWidth = 30;
            float spacing = 5;
            position.x = position.x + position.width - buttonWidth * 2 - spacing * 2;
            // 下载按钮
            Rect downloadButtonRect = new Rect(position.x, position.y, buttonWidth, position.height);
            if (GUI.Button(downloadButtonRect, "拉取", _toolbarButtonStyle))
            {
                EditorUtil.UpdateUXSystemJson();
                //刷新页面
                LoadMenuData();
            }

            // 上传按钮
            Rect uploadButtonRect = new Rect(position.x + buttonWidth + spacing, position.y, buttonWidth, position.height);
            if (GUI.Button(uploadButtonRect, "同步", _toolbarButtonStyle))
            {
                EditorUtil.UploadUXSystemJson();
            }

            // 帮助按钮
            // Rect helpButtonRect = new Rect(position.x + (buttonWidth + spacing) * 2, position.y, buttonWidth, position.height);
            // if (GUI.Button(helpButtonRect, EditorGUIUtility.IconContent("_Help"), _toolbarButtonStyle))
            // {
            //     Application.OpenURL("https://docs.unity3d.com/Manual/index.html");
            // }
        }
        private void OnEnable()
        {
            selectedChildIndex = -1;
            selectedCategoryIndex = -1;
            curItemIndex = -1;
            LoadMenuData();
            ReadMenuData();
        }
        private string[] toolbarOptions = new string[2] { "预设管理","我的设置" };
        private PageId mCurPageId;
        enum PageId{
            uxprefab,
            uxdir
            
        }
        public void OnGUI()
        {
            setBtnStyle();
            //设置一排快捷目录按钮，进入art res 
            GUILayout.BeginHorizontal();
            for (int i = 0; i < menus.Count; i++)
            {
                
                Menu selectedMenu = menus[i];
                if(selectedMenu.name == "常用快捷键"){
                     //如果为空
                    if(selectedMenu.items != null){
                        if(selectedMenu.type == MeEditorType.Hotkey){
                            for (int j = 0; j < selectedMenu.items.Count; j++)
                            {
                                ValItem item = selectedMenu.items[j];
                                if(GUILayout.Button(item.name, GUILayout.Width(100), GUILayout.Height(30))){
                                     //通过guid转换为object
                                    Object obj= UIEditorHelper.GUIDToObject<Object>(item.value);
                                    if(obj != null){
                                        Selection.activeObject = obj;
                                        EditorGUIUtility.PingObject(obj);
                                    }
                                }
                            }
                        }
                    }
                }
               
            }
            GUILayout.EndHorizontal();
            //GUILayout.BeginHorizontal();
            mCurPageId = (PageId)GUILayout.Toolbar((int)mCurPageId,toolbarOptions);
            if(mCurPageId == PageId.uxprefab){
                OpenwindowInit();
            }else if(mCurPageId == PageId.uxdir){
                OpenHotKeyInit();
            }
            //获取拖转对象
            DragObjEvent();
        }
        #region  预设管理
        public void setBtnStyle(){
             // 初始化样式
            defaultButtonStyle = new GUIStyle(GUI.skin.button);
            defaultButtonStyle.normal.textColor = Color.white;
            //默认按钮背景颜色
            defaultButtonStyle.normal.background = CommonHelper.MakeTex(200, 50, new Color(0.4f, 0.4f, 0.4f, 1.00f));
            selectedButtonStyle = new GUIStyle(GUI.skin.button);
            // 确保背景和文本颜色都正确设置
            selectedButtonStyle.normal.textColor = Color.white; // 选中时的文本颜色
            selectedButtonStyle.normal.background = CommonHelper.MakeTex(200, 50, new Color(0.24f, 0.48f, 0.90f, 1.00f)); // 选中时的背景颜色
        }
        // 辅助方法：创建一个纯色纹理
   
        Item FindItem (Object go)
        {
            for (int i = 0; i < mItems.Count; ++i)
            {
                //判断当前prefab是否存在了
                if (mItems[i].prefab == go)
                {
                    return mItems[i];
                }
            }
                
            return null;
        }
        //enum模式改成保存id和名称的结构
        const int cellPadding = 4;
        float mSizePercent = 1.0f;
        int mCellSize= 200;
        int cellSize { get { return mCellSize; } }
    

 
        /// <summary>
        /// 获取或设置当前被拖拽的对象数组。
        /// </summary>
        /// <remarks>
        /// - 当获取值时，如果DragAndDrop.objectReferences为空或长度为0，则返回null；
        /// - 否则，过滤并转换objectReferences为GameObject数组后返回。
        /// - 当设置值时，如果传入的数组不为空，则准备开始拖拽并更新objectReferences；
        /// - 如果传入的数组为空，则接受当前的拖拽操作。
        /// </remarks>
        Object[] draggedObjects
        {
            get
            {
                if (DragAndDrop.objectReferences == null || DragAndDrop.objectReferences.Length == 0)
                    return null;
                //Debug.Log("draggedObjects>>>>"+DragAndDrop.objectReferences.Length);
                //当前选择的系统类型
                PrefabType type = PrefabType.prefab;
                //当前选择的子类
                if(selectedChildIndex >= 0){
                    //获取当前选中的子目录
                    Category category = uxsystems[selectedCategoryIndex].Children[selectedChildIndex];
                    type = category.Type;
                   
                }else{
                    if(selectedCategoryIndex >= 0){
                        //获取当前选中的系统
                        SystemFather system = uxsystems[selectedCategoryIndex];
                        type = system.Type;
                    }
                }
                if(type == PrefabType.prefab){
                    return DragAndDrop.objectReferences.OfType<GameObject>().ToArray();
                }else{
                    //获取当前选中的子目录
                   return DragAndDrop.objectReferences.OfType<Texture>().ToArray();
                }
            }
    
            set
            {
                // 如果传入的值不为空，则准备开始拖拽并更新objectReferences
                if (value != null)
                {
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.objectReferences = value;
                    // draggedObjectIsOurs = true;
                }
                // 如果传入的值为空，则接受当前的拖拽操作
                else DragAndDrop.AcceptDrag();
            }
        }
        private void DragObjEvent()
        {
            Event currentEvent = Event.current;
            EventType type = currentEvent.type;
            Object[] draggeds = draggedObjects;
            bool isDragging = (draggeds != null);
            //拖转prefab到窗口 添加到对应的json文件下
            if (type == EventType.DragUpdated || type == EventType.DragPerform) 
            {
                if (isDragging)
                {
                    if (type == EventType.DragUpdated)
                    {
                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    }
                    else
                    {
                        //Debug.Log("dragged>>>>"+draggeds.Length);
                        // 拖拽完成，添加prefab到对应json文件下
                        foreach (var dragged in draggeds)
                        {
                            //Debug.Log("dragged>>>>"+dragged.name);
                            //如果已经存在不添加
                            if (FindItem(dragged) != null)
                            {
                                //当前的mitem index 
                                //外部拖拽进来的
                                if(curItemIndex < 0){
                                    continue;
                                }
                                //插入对象到当前位置
                                //鼠标落点所在的位置对应index
                                // 计算鼠标在网格中的位置
                                Vector2 mousePos = currentEvent.mousePosition;
                                int column = Mathf.FloorToInt((mousePos.x - cellPadding) / (cellSize + cellPadding));
                                int row = Mathf.FloorToInt((mousePos.y - mPos.y - cellPadding) / (cellSize + 60)); // 60为名称区域高度
                                
                                // 计算总列数
                                int columnsPerRow = Mathf.FloorToInt((Screen.width - 200 - cellPadding) / (cellSize + cellPadding));
                                int targetIndex = row * columnsPerRow + column-2;
                                
                                // 限制索引范围
                                targetIndex = Mathf.Clamp(targetIndex, 0, mItems.Count);

                                // 获取当前系统层级
                                var prefabList = selectedChildIndex == -1 ? 
                                    uxsystems[selectedCategoryIndex].Prefabs : 
                                    uxsystems[selectedCategoryIndex].Children[selectedChildIndex].Prefabs;

                                // 调整prefab在列表中的顺序
                                var item = prefabList.FirstOrDefault(p => p.guid == mItems[curItemIndex].guid);
                                if (item != null)
                                {
                                    // Debug.Log("targetIndex>>>>"+targetIndex);
                                    // Debug.Log("curItemIndex>>>>"+curItemIndex);
                                    if (curItemIndex >= 0 &&  targetIndex != curItemIndex && targetIndex >=0 && targetIndex < mItems.Count){
                                        // 更新list中curItemIndex 移动到targetIndex 位置上
                                        prefabList.Remove(item);
                                        prefabList.Insert(targetIndex, item);
                                        var temp = mItems[curItemIndex];
                                        mItems.RemoveAt(curItemIndex);
                                        mItems.Insert(targetIndex, temp);
                                    }
                                    curItemIndex = targetIndex;
                                }
                                //保存items到systemjson
                                Save();


                                continue;
                            }
                            AddItem(dragged);
                        }
                        DragAndDrop.AcceptDrag();
                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                    }
                }
            }
          
        }
        IEnumerable<Type> mEditorWindowTypes;
        private List<SystemFather> uxsystems = new List<SystemFather>();
        private List<Item> mItems = new List<Item>();
        private int selectedCategoryIndex = -1;
        //获取当前选择的子类index
        private int selectedChildIndex = -1;
        Vector2 mPos = Vector2.zero;
        //当前选择的选项
        private void LoadMenuData()
        {
            string path = Configure.ResAssetsPath + "/UXSystem.json";
            if (File.Exists(path))
            {   
                //Debug.Log("加载本地json文件");
                //Debug.Log(path);
                string json = File.ReadAllText(path);
                SystemFather[] fathers = JsonConvert.DeserializeObject<SystemFather[]>(json);
                //Category[] 数组转list
                //如果json为空 设置fathers为空
                if (fathers == null)
                {
                    fathers = new SystemFather[0];
                }else{
                    foreach (var father in fathers)
                    {
                        if (father.Children == null)
                        {
                            father.Children = new List<Category>();
                        }
                        //遍历prefabs path为空删除
                        father.Prefabs = father.Prefabs?.Where(p => !string.IsNullOrEmpty(p.path) && File.Exists(p.path)).ToList() ?? new List<PrefabItem>();
                        father.Children = father.Children.ToList();
                        foreach (var child in father.Children)
                        {
                            child.Prefabs = child.Prefabs?.Where(p => !string.IsNullOrEmpty(p.path) && File.Exists(p.path)).ToList() ?? new List<PrefabItem>();
                            // child.Prefabs = child.Prefabs.ToList();
                        }
                    }
                }
                uxsystems = fathers.ToList();
            }
        }
       
        public float SizePercent
        {
            get { return mSizePercent; }
            set 
            {
                if (mSizePercent != value)
                {
                    mSizePercent = value;
                    //最大值最小值
                    if (mSizePercent < 0.5f)
                    {
                        mSizePercent = 0.5f;
                    }
                    if (mSizePercent > 5)
                    {
                        mSizePercent = 5;
                    }
                    mCellSize = Mathf.FloorToInt(80 * SizePercent + 10);
                    EditorPrefs.SetFloat("PrefabWin_SizePercent", mSizePercent);
                }
            }
        }
        private void RefreshItem()
        {
            //当前选项
            if (selectedCategoryIndex == -1 || selectedCategoryIndex >= uxsystems.Count)
            {
                return;
            }
            //设置onguui中指执行一次
            mItems.Clear();
            //Debug.Log("刷新"+selectedCategoryIndex + " "+selectedChildIndex);
            //检查父类节点下是否有prefab list 有的话先显示
            if (uxsystems[selectedCategoryIndex].Prefabs != null && uxsystems[selectedCategoryIndex].Prefabs.Count > 0 && selectedChildIndex == -1)
            {
                //遍历子类节点下所有prefab
                //当前是否选中了子节点和父节点一起
                for (int j = 0; j < uxsystems[selectedCategoryIndex].Prefabs.Count; j++)
                {
                    PrefabItem prefabPath = uxsystems[selectedCategoryIndex].Prefabs[j];
                    if (File.Exists(prefabPath.path))
                    {
                        //获取prefab
                        Object go = AssetDatabase.LoadAssetAtPath<Object>(prefabPath.path);
                        string guid = UIEditorHelper.ObjectToGUID(go);
                        prefabPath.guid = guid;
                        prefabPath.name = go.name;
                        //判断go是图片还是prefab
                        if(go is Texture){
                            prefabPath.type = PrefabType.image;
                            prefabPath.path = AssetDatabase.GetAssetPath(go);
                        }
                        if(go is GameObject){
                            prefabPath.type = PrefabType.prefab;
                            prefabPath.path = AssetDatabase.GetAssetPath(go);
                        }
                        Item ent = new Item();
                        ent.prefab = go;
                        ent.guid = guid;
                        ent.prefabItem = prefabPath;
                        ent = GeneratePreview(ent);
                        mItems.Add(ent);
                    }
                }
                
                
            }
            if (selectedChildIndex == -1)
            {
                return;
            }
            //获取到uxsystems下子项目
            if (uxsystems[selectedCategoryIndex].Children.Count == 0)
            {
                return;
            }
            //下面是子系统的显示
            for (int j = 0; j < uxsystems[selectedCategoryIndex].Children[selectedChildIndex].Prefabs.Count; j++)
            {
                PrefabItem prefabPath = uxsystems[selectedCategoryIndex].Children[selectedChildIndex].Prefabs[j];
                //path释放存在
                if (File.Exists(prefabPath.path))
                {
                    //获取prefab
                    Object go = AssetDatabase.LoadAssetAtPath<Object>(prefabPath.path);
                    string guid = UIEditorHelper.ObjectToGUID(go);
                    prefabPath.guid = guid;
                    prefabPath.name = go.name;
                    //判断go是图片还是prefab
                    if(go is Texture){
                        prefabPath.type = PrefabType.image;
                        prefabPath.path = AssetDatabase.GetAssetPath(go);
                    }
                    if(go is GameObject){
                        prefabPath.type = PrefabType.prefab;
                        prefabPath.path = AssetDatabase.GetAssetPath(go);
                    }
                    Item ent = new Item();
                    ent.prefab = go;
                    ent.guid = guid;
                    ent.prefabItem = prefabPath;
                    ent = GeneratePreview(ent);
                    mItems.Add(ent);
                }
            }
            Repaint();
        }
        //滚动条位置
        private Vector2 m_lPost = Vector2.zero;
        private int curItemIndex = -1;
       private void OpenwindowInit()
        {
            // 使用水平布局将窗口分为左右两部分
            GUILayout.BeginHorizontal();
            // 左侧菜单栏
            GUILayout.BeginVertical(GUILayout.Width(200));
            {
                //设置为可以滚动
                m_lPost = GUILayout.BeginScrollView(m_lPost, GUILayout.Width(200));
                {
                    // 循环uxsystems 显示按钮
                    for (int i = 0; i < uxsystems.Count; i++)
                    {
                        //横向排布
                        GUILayout.BeginHorizontal();
                        {
                            GUIStyle style = (selectedCategoryIndex == i) ? selectedButtonStyle : defaultButtonStyle;
                            if (GUILayout.Button(uxsystems[i].Name, style, GUILayout.Width(150), GUILayout.Height(30)))
                            {
                                selectedCategoryIndex = i;
                                selectedChildIndex = -1;
                                curItemIndex = -1;
                                mPos = Vector2.zero;
                                RefreshItem();
                                //添加右键删除功能
                                if (Event.current.button == 1)
                                {
                                    if (selectedCategoryIndex == i){
                                        GenericMenu menu = new GenericMenu();
                                        // Debug.Log("delete system:"+ i + uxsystems[i].Name);
                                        menu.AddItem(new GUIContent("拷贝信息"), false,()=>copySystemInfo());
                                        //修改菜单
                                        menu.AddItem(new GUIContent("修改名称"), false, () => editSystemInfo());
                                        //向上移动
                                        menu.AddItem(new GUIContent("向上移动"), false, () => upSystemIndex());
                                        //向下移动
                                        menu.AddItem(new GUIContent("向下移动"), false, () => downSystemIndex());
                                        menu.AddItem(new GUIContent("删除"), false, () => deleteSystem());
                                        
                                        menu.ShowAsContext();
                                    }
                                    
                                }
                            }
                            //按钮添加右键菜单功能
                            
                            if (selectedCategoryIndex == i){
                                //打开名称面板
                                if (GUILayout.Button("+", defaultButtonStyle,GUILayout.Width(30), GUILayout.Height(30)))
                                {
                                    //OnConfirm 清空订阅

                                    UXEditorNameWin.ClearConfirmHandlers();
                                    UXEditorNameWin.OnConfirm += OnChildConfirmHandler;
                                    UXEditorNameWin.OpenWindow();
                                } 
                            }
                        }    
                        GUILayout.EndHorizontal();
                        if (selectedCategoryIndex == i)
                        {
                            GUILayout.BeginVertical();
                            {
                                for (int j = 0; j < uxsystems[i].Children.Count; j++)
                                {
                                    GUIStyle childStyle = (selectedChildIndex == j) ? selectedButtonStyle : defaultButtonStyle;
                                    if (GUILayout.Button(uxsystems[i].Children[j].Name, childStyle, GUILayout.Width(100), GUILayout.Height(25)))
                                    {
                                        selectedChildIndex = j;
                                        mPos = Vector2.zero;
                                        RefreshItem();
                                        if (Event.current.button == 1)
                                        {
                                            if (selectedChildIndex == j)
                                            {
                                                // Debug.Log("delete child:"+ j + uxsystems[i].Children[j].Name);
                                                GenericMenu menu = new GenericMenu();
                                                //j等于当前选中的子系统
                                                //子系统 拷贝信息 移动位置
                                                menu.AddItem(new GUIContent("拷贝信息"), false,()=>copySystemInfo(true));
                                                //修改菜单
                                                menu.AddItem(new GUIContent("修改名称"), false, () => editSystemInfo());
                                                menu.AddItem(new GUIContent("向上移动"), false, () => upSystemChildIndex());
                                                menu.AddItem(new GUIContent("向下移动"), false, () => downSystemChildIndex());
                                                menu.AddItem(new GUIContent("删除子项"), false, () => DeleteChildItem());
                                                menu.AddItem(new GUIContent("清空"), false, () =>clearPrefab());
                                                menu.ShowAsContext();
                                            }
                                            
                                        }
                                    }
                                }  
                            }
                            GUILayout.EndVertical();
                        }
                    }
                    // 添加按钮
                    if (GUILayout.Button("Add", defaultButtonStyle,GUILayout.Width(150), GUILayout.Height(30)))
                    {
                        //打开名称面板
                        UXEditorNameWin.ClearConfirmHandlers();
                        UXEditorNameWin.OnConfirm += OnMeEdiorConfirmHandler;
                        UXEditorNameWin.OpenWindow();
                    }
                    // 显示输入框和确认按钮
                }   
                GUILayout.EndScrollView();
            }
            GUILayout.EndVertical();

            // 右侧显示预览图
            GUILayout.BeginVertical();
            
          
            if (selectedCategoryIndex >= 0 || selectedChildIndex >= 0 )
            {
                
                //当前选择的类型
                if(selectedChildIndex >= 0){
                    //获取当前选中的子目录
                    Category category = uxsystems[selectedCategoryIndex].Children[selectedChildIndex];
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("名称"+category.Name);
                    GUILayout.Label("类型:"+category.Type.ToString());
                    GUILayout.Label("数量:"+category.Prefabs.Count);
                    GUILayout.EndHorizontal();
                }else{
                    if(selectedCategoryIndex >= 0){
                        //获取当前选中的系统
                        SystemFather system = uxsystems[selectedCategoryIndex];
                        GUILayout.BeginHorizontal();
                        GUILayout.Label("名称"+system.Name);
                        GUILayout.Label("类型:"+system.Type.ToString());
                        GUILayout.Label("数量:"+system.Prefabs.Count);
                        GUILayout.EndHorizontal();
                        
                    }
                }
                
             
                // 右侧网格方式显示prefab
                mPos = EditorGUILayout.BeginScrollView(mPos);
                int x = cellPadding;
                int y = cellPadding;
                int desHeight = 60;
                int width = Screen.width - 200 - cellPadding; // 右侧宽度
                int spacingX = cellSize + cellPadding;
                int spacingY = spacingX + desHeight;

                for (int i = 0; i < mItems.Count; i++)
                {
                    Item item = mItems[i];
                    if (item == null) continue;

                    Rect rect = new Rect(x, y, cellSize, cellSize + desHeight);
                    Rect inner = new Rect(rect.x, rect.y, cellSize, cellSize);
                    inner.xMin += 2f;
                    inner.xMax -= 2f;
                    inner.yMin += 2f;
                    inner.yMax -= 2f;
                    rect.yMax -= 1f;
                     // 检测右键点击事件
                    Event currentEvent = Event.current;
                    if (currentEvent.type == EventType.ContextClick && inner.Contains(currentEvent.mousePosition))
                    {
                        ShowContextMenu(currentEvent.mousePosition, item);
                        currentEvent.Use();
                    }
            
                    
                    // 读取预览的图片展示出来
                    if (item.tex != null)
                    {
                        GUI.DrawTexture(inner, item.tex);
                    }
                    else
                    {
                        GUI.Box(inner, "");
                    }
                    //绘制名称
                    var labelPos = new Rect(rect.x, rect.y + cellSize, cellSize, desHeight);
                    var labelStyle = EditorStyles.label;
                    labelStyle.fontSize = (int)(_labelDefaultFontSize * SizePercent);
                    labelStyle.alignment = TextAnchor.UpperLeft;
                    labelStyle.fontSize = _labelDefaultFontSize;
                    labelStyle.alignment = TextAnchor.MiddleCenter;
                    //是否选中了当前item
                    if (curItemIndex == i)
                    {
                        var recordColor = GUI.backgroundColor;
                        GUI.backgroundColor = Color.yellow;
                        GUI.Box(labelPos, new GUIContent(""));
                        GUI.backgroundColor = recordColor;
                    }
                    {
                        //绘制名称
                        //设置名称自动换行
                        labelStyle.wordWrap = true;
                        string name = "";
                        if (item.prefab != null) {
                            name = item.prefab.name +"\n"+ item.prefabItem.desc;
                        }
                        // string name = item.prefab.name +"\n"+ item.prefabItem.desc;
                        GUI.Label(labelPos, name, labelStyle);
                        //恢复默认
                        labelStyle.wordWrap = false;
                    }
                    //鼠标选中拖拽item
                    if (rect.Contains(currentEvent.mousePosition))
                    {
                        if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0)
                        {
                            //单击文本名称变颜色
                            if (currentEvent.clickCount == 1)
                            {
                               //当前位置画一个色块
                                curItemIndex = i;
                                
                                currentEvent.Use();
                            }
                            if (currentEvent.clickCount == 2){
                                SelectItem(item);
                                currentEvent.Use();
                            }  
                            
                        }
                        if (currentEvent.type == EventType.MouseDrag && currentEvent.button == 0)
                        {
                            DragAndDrop.PrepareStartDrag();
                            DragAndDrop.objectReferences = new Object[] { item.prefab };
                            DragAndDrop.StartDrag(item.prefabItem.name);
                            currentEvent.Use();
                        }
                    }
                    
                    //鼠标滚动事件，用于缩放prefab的显示
                    if (currentEvent.type == EventType.ScrollWheel)
                    {
                        // 检查是否按下了Ctrl键
                        if (Event.current.control)
                        {
                            float delta = currentEvent.delta.y;
                            SizePercent -= delta * 0.02f;
                            //更新试图
                            // Repaint();
                            currentEvent.Use();
                        }
                    }
                    x += spacingX;
                    if (x + spacingX > width)
                    {
                        y += spacingY;
                        x = cellPadding;
                    }
                    GUILayout.Space(y);
                }
                
                GUILayout.EndScrollView();
            }
            SizePercent = EditorGUILayout.Slider(SizePercent, 0, 5);
            
            
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();
        }
            // 定义一个单独的方法来处理事件
        private void OnMeEdiorConfirmHandler(string name, PrefabType type,string menuPath="")
        {
            if (!string.IsNullOrEmpty(name))
            {
                SystemFather category = new SystemFather();
                category.Id = uxsystems.Count;
                category.MenuPath = menuPath;
                category.Type = type;
                category.Name = name;
                category.Children = new List<Category>();
                category.Prefabs = new List<PrefabItem>();
                uxsystems.Add(category);
                Save();
            }
            else
            {
                Debug.LogWarning("Category name cannot be empty.");
            }
        }
        private void OnChildConfirmHandler(string name, PrefabType type,string menuPath="")
        {
            if (!string.IsNullOrEmpty(name))
            {
                Category category = new Category();
                category.Type = type;
                category.Id = uxsystems.Count;
                category.Name = name;
                category.Prefabs = new List<PrefabItem>();
                uxsystems[selectedCategoryIndex].Children.Add(category);
                Save();

            }
            else
            {
                Debug.LogWarning("Category name cannot be empty.");
            }
        }
        private void ShowContextMenu(Vector2 position, Item item)
        {
            GenericMenu menu = new GenericMenu();
            menu.AddItem(new GUIContent("查找引用"), false, () => FindInProject(item));
            menu.AddItem(new GUIContent("修改"), false, () => UpdateItem(item));
            menu.AddItem(new GUIContent("重绘"), false, () => RefreshItem(item));
            menu.AddItem(new GUIContent("删除"), false, () => DeleteItem(item));
            menu.ShowAsContext();
        }
        //空白处菜单
        private void RefreshItem(Item item){
            //刷新当前预览图
            GeneratePreview(item, true);
            RefreshItem();
        }
        private void FindInProject(Item item){
            //打开MeEditor窗口，并把item传递过去
            MeEditor.MeEditorWindow.OpenGUILayoutExample();
            MeEditor.MeEditorWindow.SetItem(item.prefab);

        }
        private void UpdateItem(Item item)
        {
           //打开修改窗口
            
            UXEditorChildWin.OnConfirm += (prefabItem) =>
            {
                //更新当前item

                item.prefabItem = prefabItem;
                Save();
                RefreshItem();
            };
            UXEditorChildWin.OpenWindow(item.prefabItem);
        }
        private void SelectItem(Item item)
        {
            Object prefab = item.prefab;
            if (prefab != null)
            {
                Selection.activeObject = item.prefab;
                EditorGUIUtility.PingObject(item.prefab);
            }
            
        }
        //删除子系统
        private void deleteSystem()
        {
            //删除选中的
            int i = selectedCategoryIndex;
           // Debug.Log("delete system:" + i);
            if (i >= 0 && i < uxsystems.Count)
            {
                uxsystems.RemoveAt(i);
                selectedCategoryIndex = -1;
                selectedChildIndex = -1;
                curItemIndex = -1;
                
                RefreshItem();
            }
        }
        private void clearPrefab(){
            //当前选中的子系统清空
            if(selectedChildIndex != -1){
                uxsystems[selectedCategoryIndex].Children[selectedChildIndex].Prefabs.Clear();
            }
            Save();
            RefreshItem();
        }
        private void editSystemInfo(){
            //打开修改窗口
            UXEditorNameWin.ClearConfirmHandlers();
            UXEditorNameWin.OnConfirm += updateSysInfoConfirmHandler;
            if(selectedChildIndex >= 0) {
                UXEditorNameWin.OpenWindow(uxsystems[selectedCategoryIndex].Children[selectedChildIndex].Name);
            }else{
                UXEditorNameWin.OpenWindow(uxsystems[selectedCategoryIndex].Name);
            }
            // UXEditorNameWin.OpenWindow(uxsystems[selectedCategoryIndex]);
        }
        private void updateSysInfoConfirmHandler(string name, PrefabType type,string menuPath=""){
            if (!string.IsNullOrEmpty(name))
            {
                //是否子系统也选择了
                if (selectedChildIndex >= 0){
                    //子系统
                    uxsystems[selectedCategoryIndex].Children[selectedChildIndex].Name = name;
                    //uxsystems[selectedCategoryIndex].Children[selectedChildIndex].MenuPath = menuPath;
                }else{
                    //系统
                    uxsystems[selectedCategoryIndex].Name = name;
                    //uxsystems[selectedCategoryIndex].MenuPath = menuPath;
                }
                Save();
                RefreshItem();
            }
            else
            {
                Debug.LogWarning("Category name cannot be empty.");
            }

        }
        private void upSystemIndex()
        {
            //当前子项 systems数组中排序上向上
            int i = selectedCategoryIndex;
            if (i >= 1 && i < uxsystems.Count)
            {
                SystemFather system = uxsystems[i];
                SystemFather system2 = uxsystems[i - 1];
                uxsystems.RemoveAt(i);
                uxsystems.Insert(i, system2);
                uxsystems.RemoveAt(i - 1);
                uxsystems.Insert(i-1, system);
                Save();
                RefreshItem();
            }
           
        }
        private void downSystemIndex()
        {
            //当前子项 systems数组中排序下向下
            int i = selectedCategoryIndex;
            if (i >= 0 && i < uxsystems.Count - 1)
            {
                SystemFather system = uxsystems[i];
                SystemFather system2 = uxsystems[i + 1];
                uxsystems.RemoveAt(i);
                uxsystems.Insert(i, system2);
                uxsystems.RemoveAt(i + 1);
                uxsystems.Insert(i + 1, system);
                Save();
                RefreshItem();
            }
        }
           private void upSystemChildIndex()
        {
            //当前子项 systems数组中排序上向上
            int i = selectedChildIndex;
            if (i >= 1 && i < uxsystems[selectedCategoryIndex].Children.Count)
            {
                Category system = uxsystems[selectedCategoryIndex].Children[i];
                Category system2 = uxsystems[selectedCategoryIndex].Children[i-1];
                uxsystems[selectedCategoryIndex].Children.RemoveAt(i);
                uxsystems[selectedCategoryIndex].Children.Insert(i, system2);
                uxsystems[selectedCategoryIndex].Children.RemoveAt(i - 1);
                uxsystems[selectedCategoryIndex].Children.Insert(i-1, system);
                Save();
                RefreshItem();
            }
           
        }
        private void downSystemChildIndex()
        {
            //当前子项 systems数组中排序下向下
            int i = selectedChildIndex;
            if (i >= 0 && i < uxsystems[selectedCategoryIndex].Children.Count -1 )
            {
                Category system = uxsystems[selectedCategoryIndex].Children[i];
                Category system2 = uxsystems[selectedCategoryIndex].Children[i+1];
                uxsystems[selectedCategoryIndex].Children.RemoveAt(i);
                uxsystems[selectedCategoryIndex].Children.Insert(i, system2);
                uxsystems[selectedCategoryIndex].Children.RemoveAt(i + 1);
                uxsystems[selectedCategoryIndex].Children.Insert(i+1, system);
                Save();
                RefreshItem();
            }
        }
        private void copySystemInfo(bool isChild = false){
            //复制选中的
            int i = selectedCategoryIndex;
            if (isChild)
            {
                i = selectedChildIndex;
                if (i >= 0 && i < uxsystems[selectedCategoryIndex].Children.Count)
                {
                    Category system = uxsystems[selectedCategoryIndex].Children[i];
                    string clipboardText = "";
                    foreach (var prefabItem in system.Prefabs)
                    {
                        clipboardText += prefabItem.name + "\n" + prefabItem.desc + "\n";
                    }
                    // 复制到剪贴板
                    GUIUtility.systemCopyBuffer = clipboardText;
                    //飘窗提示
                    Debug.Log("复制成功");
                    //EditorUtility.DisplayDialog("复制成功", "已复制到剪贴板", "确定");

                }

            }else{
                if (i >= 0 && i < uxsystems.Count)
                {
                    SystemFather system = uxsystems[i];
                    //复制当前系统下 prefabItems 的名称和描述
                    string clipboardText = "";
                    foreach (var prefabItem in system.Prefabs)
                    {
                        clipboardText += prefabItem.name + "\n" + prefabItem.desc + "\n";
                    }
                    // 复制到剪贴板
                    GUIUtility.systemCopyBuffer = clipboardText;
                    //弹窗提示已经复制
                    Debug.Log("复制成功");
                    //EditorUtility.DisplayDialog("复制成功", "已复制到剪贴板", "确定");
                    // Debug.Log("copy system:" + i);
                }
            }
        
                  
        }
        private void DeleteChildItem(){
            int index = selectedChildIndex;
          
            if (selectedCategoryIndex >= 0 && selectedCategoryIndex < uxsystems.Count)
            {
                //Category selectedCategory = uxsystems[selectedCategoryIndex].Children[index];
                uxsystems[selectedCategoryIndex].Children.RemoveAt(index);
                selectedCategoryIndex = -1;
                selectedChildIndex = -1;
                curItemIndex = -1;
                Save();
                RefreshItem();
            }
        }
        private void DeleteItem(Item item)
        {
            // 删除逻辑
            if (selectedCategoryIndex >= 0 && selectedCategoryIndex < uxsystems.Count)
            {
                //如果选择的是父类下的prerfab
                PrefabItem prefabPath = item.prefabItem;
                if (selectedChildIndex < 0)
                {
                    //删除父类下的prerfab
                    uxsystems[selectedCategoryIndex].Prefabs.Remove(prefabPath);
                }
                else
                {
                    Category  selectedCategory = uxsystems[selectedCategoryIndex].Children[selectedChildIndex];
                    // prefabPath = AssetDatabase.GUIDToAssetPath(item.guid);
                    selectedCategory.Prefabs.Remove(prefabPath);
                }
                
                mItems.Remove(item);
                Save();
                RefreshItem();
            }
        }

        void AddItem (Object go)
        {
            string guid = UIEditorHelper.ObjectToGUID(go);
            PrefabItem prefabPath = new PrefabItem();
            prefabPath.guid = guid;
            prefabPath.name = go.name;
            //判断go是图片还是prefab
            if(go is Texture){
                prefabPath.type = PrefabType.image;
                prefabPath.path = AssetDatabase.GetAssetPath(go);
            }
            if(go is GameObject){
                prefabPath.type = PrefabType.prefab;
                prefabPath.path = AssetDatabase.GetAssetPath(go);
            }
            Item ent = new Item();
            ent.prefab = go;
            ent.guid = guid;
            ent.prefabItem = prefabPath;
            ent = GeneratePreview(ent);
           
            mItems.Add(ent);
            //更新uxsystems
            //如果没有选中子系统 直接添加到父类下
            if(selectedChildIndex == -1){
                if(uxsystems[selectedCategoryIndex].Prefabs == null){
                    uxsystems[selectedCategoryIndex].Prefabs = new List<PrefabItem>();
                }
                uxsystems[selectedCategoryIndex].Prefabs.Add(prefabPath);
            }else{
                uxsystems[selectedCategoryIndex].Children[selectedChildIndex].Prefabs.Add(prefabPath);
            }

            Save();
        }
        //保存uxsystem对象到本地json
        private void Save(){
            string path = Configure.ResAssetsPath + "/UXSystem.json";
           
            //保存到本地json文件
            if (File.Exists(path))
            {
                //数组对象转json
                string json;
                try
                {
                    if (uxsystems == null)
                    {
                        json = "null"; // 或者根据业务逻辑返回合适的默认值
                    }
                    else
                    {
                        // 确保 uxsystems 中不包含敏感信息
                        json = JsonConvert.SerializeObject(uxsystems);
                    }
                }
                catch (JsonSerializationException ex)
                {
                    // 记录日志并返回默认值或抛出自定义异常
                    Console.Error.WriteLine($"序列化失败: {ex.Message}");
                    json = "序列化失败";
                    // 或者 throw new CustomException("序列化失败", ex);
                }
                catch (Exception ex)
                {
                    // 记录日志并返回默认值或抛出自定义异常
                    Console.Error.WriteLine($"未知错误: {ex.Message}");
                    json = "未知错误";
                    // 或者 throw new CustomException("未知错误", ex);
                }
                // Debug.Log(json);
                File.WriteAllText(path, json);
            }
           
        }
        public Item GeneratePreview (Item item, bool isReCreate = false)
        {
            if (item == null) return null;
            if (item.prefab != null)
            {
                //判断prefab为图片还是prefab
                if(item.prefab as GameObject){
                    //Debug.Log("prefab>>>>"+item.prefab.name);
                    string preview_path = Configure.ResAssetsPath + "/Preview/" + item.prefab.name + ".png";
                    if (!isReCreate && File.Exists(preview_path))
                    {
                        Texture texture = UIEditorHelper.LoadTextureInLocal(preview_path);
                        if (texture != null)
                        {
                            item.tex = texture;
                        }
                        else
                        {
                            Debug.LogWarning($"Failed to load texture from {preview_path}");
                        }
                    }
                    else
                    {
                        Texture Tex = UIEditorHelper.GetAssetPreview(item.prefab as GameObject);
                        if (Tex != null)
                        {
                            // 销毁旧的纹理
                            DestroyTexture(item);
                            item.tex = Tex;
                            UIEditorHelper.SaveTextureToPNG(Tex, preview_path);
                        }
                        else
                        {
                            Debug.LogWarning($"Failed to generate preview for {item.prefab.name}");
                        }
                    }
                }
                if (item.prefab as Texture2D)
                {
                    item.tex = item.prefab as Texture2D;
                }
                
                return item;
            }

            // 确保所有代码路径都有返回值
            return null;
        }
        void DestroyTexture (Item item)
        {
            if (item != null && item.tex != null)
            {
                DestroyImmediate(item.tex);
                item.dynamicTex = false;
                item.tex = null;
            }
        }
        #endregion
        //快捷功能
        #region 常用说明和功能快捷键
    
        class Menu{
            public string name;
            public MeEditorType type;
            public List<ValItem> items;
        }
        class ValItem{
            public string name;
            public string value;
        }
        private List<Menu> menus = new List<Menu>();
        private int selectedMenuIndex = -1;
        // private GUIStyle defaultButtonStyle;
        // private GUIStyle selectedButtonStyle;

        private bool isAddValue = false;
        private void OpenHotKeyInit()
        {

            setBtnStyleDir();

            //左边显示菜单列表，右侧显示具体内容滚动列表
            // 使用水平布局将窗口分为左右两部分
            GUILayout.BeginHorizontal();
            // 左侧菜单栏
            GUILayout.BeginVertical(GUILayout.Width(180));
            {
                //mens菜单列表
                for (int i = 0; i < menus.Count; i++)
                {
                    GUILayout.BeginHorizontal();
                    GUIStyle style = (selectedMenuIndex == i) ? selectedButtonStyle : defaultButtonStyle;
                    if (GUILayout.Button(menus[i].name, style,GUILayout.Width(150), GUILayout.Height(30)))
                    {
                        selectedMenuIndex = i;
                        isAddValue = false;
                        //Debug.Log("selectedMenuIndex--->" + selectedMenuIndex);
                    }
                    if(selectedMenuIndex == i){
                        //右键删除菜单
                        if (GUILayout.Button("X",GUILayout.Width(20), GUILayout.Height(20)))
                        {
                            //删除的弹窗提示
                            if (EditorUtility.DisplayDialog("提示", "确定要删除吗", "确定")){
                                //当前item删除
                                menus.RemoveAt(selectedMenuIndex);
                                Save();
                            }
                        }
                    }

                    GUILayout.EndHorizontal();
                }
                //添加按钮
                if (GUILayout.Button("添加", defaultButtonStyle,GUILayout.Width(120), GUILayout.Height(30)))
                {
                    // 取消之前的订阅
                    MeEditorNameWin.OnMeEdiorConfirm -= OnMeEdiorConfirmHandler;
                    // 添加新的订阅
                    MeEditorNameWin.OnMeEdiorConfirm += OnMeEdiorConfirmHandler;
                    MeEditorNameWin.OpenWindow();
                
                }
            }
            GUILayout.EndVertical();
            GUILayout.BeginVertical();
            {
                //如果为空不显示右侧内容
                if(selectedMenuIndex == -1 || selectedMenuIndex >= menus.Count ){
                    GUILayout.Label("请选择左侧菜单");
                    
                }else{
                     //显示菜单内容
                    Menu selectedMenu = menus[selectedMenuIndex];
                   
                    //如果为空
                    if(selectedMenu.items == null){
                        GUILayout.Label("请添加内容");
                    }else{
                        if(selectedMenu.type == MeEditorType.Hotkey){
                            for (int i = 0; i < selectedMenu.items.Count; i++)
                            {
                                GUILayout.BeginHorizontal();
                                
                            
                                ValItem item = selectedMenu.items[i];
                                //通过guid转换为object
                                Object obj= UIEditorHelper.GUIDToObject<Object>(item.value);
                                //文字换行

                                GUILayout.Label(item.name,GUILayout.Width(100));
                                //展示obj
                                if(obj == null){
                                    GUILayout.Label(item.name + " : " + item.value + "--->该对象已删除");
                                }else{
                                    EditorGUILayout.ObjectField("", obj, typeof(Object), true,GUILayout.Width(150));
                                }
                                
                                //删除按钮和修改按钮
                                if (GUILayout.Button("X",GUILayout.Width(20), GUILayout.Height(20)))
                                {
                                //删除的弹窗提示
                                    if (EditorUtility.DisplayDialog("提示", "确定要删除吗", "确定")){
                                        //当前item删除
                                        selectedMenu.items.RemoveAt(i);
                                        menus[selectedMenuIndex].items = selectedMenu.items;
                                        Save();
                                    }
                                }
                                
                                
                                GUILayout.EndHorizontal();
                            }
                        }else{
                            for (int i = 0; i < selectedMenu.items.Count; i++)
                            {
                                GUILayout.BeginHorizontal();
                                ValItem item = selectedMenu.items[i];
                                GUILayout.Label(item.name,GUILayout.Width(100));
                                //显示值信息
                                GUILayout.Label(item.value);
                                if (GUILayout.Button("复制",GUILayout.Width(40), GUILayout.Height(20)))
                                {
                                   //复制值内容
                                   EditorGUIUtility.systemCopyBuffer = item.value;
                                   //飘窗提示
                                   Debug.Log("复制成功");
                                }
                                if (GUILayout.Button("X",GUILayout.Width(20), GUILayout.Height(20)))
                                {
                                    //删除的弹窗提示
                                    if (EditorUtility.DisplayDialog("提示", "确定要删除吗", "确定")){
                                        //当前item删除
                                        selectedMenu.items.RemoveAt(i);
                                        menus[selectedMenuIndex].items = selectedMenu.items;
                                        Save();
                                    }
                                }
                                GUILayout.EndHorizontal();
                            }
                        }
                    }
                     //添加新的内容
                    if (GUILayout.Button("Add", defaultButtonStyle,GUILayout.Width(120), GUILayout.Height(20)))
                    {
                        //取消之前的订阅
                        isAddValue = true;
                    }
                    if(isAddValue){
                        ShowAddValue(selectedMenu);
                    }
                    
                }
               
            
            }
            GUILayout.EndVertical();

            GUILayout.EndHorizontal();
        }
        string itemName = "";
        string itemValue = "";
        Object setObj = null;
        private void ShowAddValue(Menu selectedMenu)
        {
 
            //输入名称
            GUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("名称",GUILayout.Width(60));

            itemName = EditorGUILayout.TextField(itemName);
            GUILayout.EndHorizontal();
            
            //如果是text
            if(selectedMenu.type == MeEditorType.Hotkey){
                GUILayout.BeginHorizontal();
                GUILayout.Label("快捷对象:",GUILayout.Width(60));   
                setObj = EditorGUILayout.ObjectField(setObj, typeof(Object), true);
                //获得对象的guid
                itemValue = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(setObj));
                GUILayout.EndHorizontal();
            }else{
                GUILayout.BeginHorizontal();
                GUILayout.Label("内容:",GUILayout.Width(60));
                itemValue = EditorGUILayout.TextField(itemValue); 
                GUILayout.EndHorizontal();
            }
            GUILayout.BeginHorizontal();
            //保存按钮
            if (GUILayout.Button("保存", defaultButtonStyle,GUILayout.Width(60), GUILayout.Height(30)))
            {
                // 保存数据
                ValItem valItem = new ValItem();
                valItem.name = itemName;
                valItem.value = itemValue;
                selectedMenu.items.Add(valItem);
                menus[selectedMenuIndex] = selectedMenu;
                // 保存数据
                DirSave();
                // 取消添加
                
                itemName = "";
                itemValue = "";
                setObj = null;
                isAddValue = false;
            }
            //取消按钮
            if (GUILayout.Button("取消", defaultButtonStyle,GUILayout.Width(60), GUILayout.Height(30)))
            {
                // 取消添加
                
                itemName = "";
                itemValue = "";
                setObj = null;
                isAddValue = false;
            }
            GUILayout.EndHorizontal();
        }
        // 定义一个单独的方法来处理事件
        private void OnMeEdiorConfirmHandler(string name, MeEditorType type)
        {
            if (!string.IsNullOrEmpty(name))
            {
                // 创建
                //Debug.Log("name--->" + menus.Count);
                Menu menu = new Menu();
                menu.name = name;
                menu.type = type;
                menu.items = new List<ValItem>();
                menus.Add(menu);
                //Debug.Log("name--->" + menus.Count);
                // 保存到本地
                Save();
            }
        }
        /// <summary>
        /// 读取菜单数据
        //设置菜单样式
        private void setBtnStyleDir()
        {
             // 初始化样式
            defaultButtonStyle = new GUIStyle(GUI.skin.button);
            defaultButtonStyle.normal.textColor = Color.white;
            //默认按钮背景颜色
            defaultButtonStyle.normal.background = CommonHelper.MakeTex(200, 50, new Color(0.4f, 0.4f, 0.4f, 1.00f));
            selectedButtonStyle = new GUIStyle(GUI.skin.button);
            // 确保背景和文本颜色都正确设置
            selectedButtonStyle.normal.textColor = Color.white; // 选中时的文本颜色
            selectedButtonStyle.normal.background = CommonHelper.MakeTex(200, 50, new Color(0.24f, 0.48f, 0.90f, 1.00f)); // 选中时的背景颜色

        }
        //如果没有内容json文件 则读取本地文件

        private void ReadMenuData()
        {
            string menuPath = Configure.ResAssetsPath + "/MenuData.json";
            if (File.Exists(menuPath))
            {
                string json = File.ReadAllText(menuPath);
                List<Menu> readMenus = JsonConvert.DeserializeObject<List<Menu>>(json);
                for (int i = 0; i < readMenus.Count; i++)
                {
                    //Debug.Log("readMenus[i].name--->" + readMenus[i].name);
                    //Debug.Log("readMenus[i].items.Count--->" + readMenus[i].items.Count);
                    readMenus[i].items = readMenus[i].items.ToList();
                }
                menus = readMenus.ToList();
            }
            
        }
        private void DirSave()
        {
            //Debug.Log("保存");
            string menuPath = Configure.ResAssetsPath + "/MenuData.json";
            string json = JsonConvert.SerializeObject(menus);
            //保存到本地
            File.WriteAllText(menuPath, json);
            Debug.Log("保存成功");
        }
        #endregion
    
    }

    //弹出窗口 设置父类菜单名称
    public class UXEditorNameWin : EditorWindow
    {
        private string systemName;
        private PrefabType type;
        private string menuPath;
        public static event Action<string,PrefabType,string> OnConfirm;
        public static void OpenWindow(string name = null)
        {
            //设置窗口的大小
            UXEditorNameWin window = GetWindow<UXEditorNameWin>();
            window.minSize = new Vector2(300, 200);
            window.maxSize = new Vector2(300, 200);
            //窗口弹出位置设置当前鼠标的位置  位置加上UIPreabWin的坐标
            window.minSize = window.maxSize = new Vector2(300, 200);
            window.titleContent = new GUIContent("设置系统名称");
           
            // Vector2 mousePos = Event.current.mousePosition;
            // //UXPreabWin窗口坐标
            Vector2 pos = new Vector2(UXPreabWin.GetWindow<UXPreabWin>().position.x, UXPreabWin.GetWindow<UXPreabWin>().position.y);
            // mousePos += pos;
            // //鼠标位置不对 重新检查
            // if (mousePos.x == 0 && mousePos.y == 0)
            // {
            //     mousePos = new Vector2(Screen.width / 2, Screen.height / 2);
            // }
            // window.position = new Rect(mousePos.x, mousePos.y, 300, 200);

            window.position = new Rect(pos.x+200, pos.y+100, 300, 100);
            
            if (name != null)
            {
                window.SetSysInfo(name);
            }
            // window.Show();
            //窗口始终在最前面
            window.ShowUtility();
            window.Focus();
        }
        //设置名称窗口
        public void SetSysInfo(string name){
            systemName = name;
            // type = finfo.Type;
            // menuPath = finfo.MenuPath;
        }
        public static void ClearConfirmHandlers()
        {
            OnConfirm = null;
        }
        private void OnGUI()
        {
            systemName = EditorGUILayout.TextField("系统名称", systemName);
            GUILayout.Space(10);
            //下拉框选择类型
            type = (PrefabType)EditorGUILayout.EnumPopup("选择类型", type);
            GUILayout.Space(10);
            //指定系统的菜单目录
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("OK"))
            {
                //传递名称到下一个界面
                  // 传递名称到下一个界面
                OnConfirm?.Invoke(systemName,type,menuPath);
                Close();
            }
            if (GUILayout.Button("Cancel"))
            {
                Close();
            }
            GUILayout.EndHorizontal();
        }
    }
    //编辑子项目的界面
    public class UXEditorChildWin : EditorWindow
    {
        private PrefabItem item;
        public static event Action<PrefabItem> OnConfirm;
        public static void OpenWindow(PrefabItem item)
        {
            UXEditorChildWin window = GetWindow<UXEditorChildWin>();
            window.minSize = new Vector2(450, 260);
            window.maxSize = new Vector2(450, 260);
            window.titleContent = new GUIContent("编辑子项目");
            window.item = item;
            window.Show();
        }
        //清空订阅
        public void ClearConfirmHandlers()
        {
            OnConfirm = null;
        }
        private void OnGUI()
        {
            GUILayout.Label("描述", EditorStyles.boldLabel);
            item.desc = EditorGUILayout.TextField("", item.desc);
            //展示的图片
            GUILayout.Label("预览图片", EditorStyles.boldLabel);
            GUILayout.Label(item.image);
            //选择图片
            if (GUILayout.Button("选择图片"))
            {
                string path = EditorUtility.OpenFilePanel("选择图片", "", "png,jpg,jpeg");
                if (!string.IsNullOrEmpty(path))
                {
                    item.image = path;
                }
                //替换原来目录下的文件
                string newPath = Configure.ResAssetsPath + "/Preview/" + item.name + ".png";
                if (File.Exists(newPath))
                {
                    File.Delete(newPath);
                }
                File.Copy(path, newPath);
                item.image = newPath;
            }
            GUILayout.Space(10);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("OK"))
            {
                OnConfirm?.Invoke(item);
                Close();
            }
            if (GUILayout.Button("Cancel"))
            {
                Close();
            }
            GUILayout.EndHorizontal();
        }
    }
        //弹出窗口 设置名称
    public class MeEditorNameWin : EditorWindow
    {
        private string systemName;
        private MeEditorType type = MeEditorType.Text;
        public static event Action<string,MeEditorType> OnMeEdiorConfirm;
        public static void OpenWindow()
        {
            //设置窗口的大小
            MeEditorNameWin window = GetWindow<MeEditorNameWin>();
            window.minSize = new Vector2(300, 100);
            window.maxSize = new Vector2(300, 100);
            //窗口弹出位置设置当前鼠标的位置  位置加上UIPreabWin的坐标
            window.minSize = window.maxSize = new Vector2(300, 100);
            window.titleContent = new GUIContent("设置系统名称");
            Vector2 mousePos = Event.current.mousePosition;
            //UIPreabWin窗口坐标
            Vector2 pos = new Vector2(UXPreabWin.GetWindow<UXPreabWin>().position.x, UXPreabWin.GetWindow<UXPreabWin>().position.y);
            mousePos += pos;
            //鼠标位置不对 重新检查
            if (mousePos.x == 0 && mousePos.y == 0)
            {
                mousePos = new Vector2(Screen.width / 2, Screen.height / 2);
            }
            window.position = new Rect(mousePos.x, mousePos.y, 300, 100);
            
            window.Show();
        }
        private void OnGUI()
        {
            systemName = EditorGUILayout.TextField("系统名称", systemName);
            GUILayout.Space(10);
            //下拉框选择类型
            type = (MeEditorType)EditorGUILayout.EnumPopup("选择类型", type);
            GUILayout.Space(10);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("OK"))
            {
                OnMeEdiorConfirm?.Invoke(systemName,type);
                Close();
            }
            if (GUILayout.Button("Cancel"))
            {
                Close();
            }
            GUILayout.EndHorizontal();
        }
    }
 
}